package com.example.aesdemo.utils

import android.util.Base64
import android.util.Log
import java.nio.charset.StandardCharsets
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

/**
 * @author: njb
 * @date:   2025/7/19 16:30
 * @desc:   描述
 */
object AESEnCryptUtils {
    private val ALGORITHM: String = "AES"
    private val TRANSFORMATION = "AES/CBC/PKCS7Padding"
    private val TAG = "AESEnCryptUtils"

    @Throws(Exception::class)
    fun encrypt(keyText: String) {
        // 1. 密钥（严格核对字符）
        val keyStr = Constants.AES_KEY
        val key = keyStr.toByteArray(StandardCharsets.UTF_8)
        Log.d(TAG,"密钥长度（字节）：" + key.size) // 必须32
        Log.d(TAG,"密钥16进制：" + bytesToHex(key)) // 用于对比正确性

        // 2. 明文
        val plaintext = keyText
        val data = plaintext.toByteArray(StandardCharsets.UTF_8)
        Log.d(TAG,"明文16进制：" + bytesToHex(data)) // 应为313233

        // 3. IV（16个1）
        val ivStr = Constants.AES_IV
        val iv = ivStr.toByteArray(StandardCharsets.UTF_8)
        Log.d(TAG,"IV长度（字节）：" + iv.size) // 必须16
        Log.d(TAG,"IV16进制：" + bytesToHex(iv)) // 应为313131...31（16个）

        // 4. 加密算法验证
        val cipher = Cipher.getInstance(TRANSFORMATION)
        val keySpec = SecretKeySpec(key, ALGORITHM)
        Log.d(TAG,"密钥强度（位）：" + keySpec.encoded.size * 8) // 必须256
        val ivSpec = IvParameterSpec(iv)
        Log.d(TAG,"密文16进制：" + String(iv))
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec)

        // 5. 加密并验证密文
        val encryptedBytes = cipher.doFinal(data)
        Log.d(TAG,"密文16进制：" + bytesToHex(encryptedBytes))
        Log.d(TAG,
            "密文Base64：" + Base64.encodeToString(
                encryptedBytes,
                Base64.DEFAULT
            )
        )

        // 6. 合并并编码
        val combined = ByteArray(iv.size + encryptedBytes.size)
        System.arraycopy(iv, 0, combined, 0, iv.size)
        System.arraycopy(encryptedBytes, 0, combined, iv.size, encryptedBytes.size)
        val finalResult = Base64.encodeToString(combined, Base64.DEFAULT)
/*        val ivHex = bytesToHex(iv)
        val encryptedHex = bytesToHex(encryptedBytes)

        // 使用StringBuilder拼接十六进制字符串
        val combinedHex = StringBuilder()
            .append(ivHex)
            .append(encryptedHex)
            .toString()

        // 7. 对拼接后的十六进制字符串进行Base64编码
        val combinedBytes = combinedHex.toByteArray(StandardCharsets.UTF_8)
        val finalResult = Base64.encodeToString(combinedBytes, Base64.DEFAULT)*/

        // 最终验证
        Log.d(TAG, "最终结果：$finalResult")
    }


    @Throws(java.lang.Exception::class)
    fun decryptFromBase64(key: ByteArray, input: String): String {
        // 1. 提取IV部分 (前22字符)
        var ivBase64 = input.substring(0, 22)
        // 补全Base64填充
        if (ivBase64.length % 4 != 0) {
            ivBase64 += "==".substring(0, 4 - (ivBase64.length % 4))
        }
        val iv = Base64.decode(ivBase64, Base64.DEFAULT)

        // 2. 提取密文部分
        val dataBase64 = input.substring(22)
        val encryptedBytes = Base64.decode(dataBase64, Base64.DEFAULT)

        // 3. 初始化解密
        val cipher = Cipher.getInstance(TRANSFORMATION)
        val keySpec = SecretKeySpec(key, ALGORITHM)
        val ivps = IvParameterSpec(iv)
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivps)

        // 4. 执行解密
        return String(cipher.doFinal(encryptedBytes), StandardCharsets.UTF_8)
    }

    // 字节数组转16进制（用于验证）
    private fun bytesToHex(bytes: ByteArray): String {
        val sb = StringBuilder()
        for (b in bytes) {
            sb.append(String.format("%02x", b))
        }
        return sb.toString()
    }
}